package com.yotoodesign.core.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.ImageView;

/**
 * 
 * 第一个参数 就是图片下载路径的url 
 * 第二个参数是 下载的进度 
 * 第三个参数就是异步任务执行完毕后的返回值
 * 
 * @author Administrator
 * 
 */


public class LoadImageAsynTask extends AsyncTask<String, Void, Bitmap> {
	LoadImageAsynTaskCallback loadImageAsynTaskCallback;
	
	public static int defaultImg;
	
	

	public LoadImageAsynTask(LoadImageAsynTaskCallback loadImageAsynTaskCallback) {
		this.loadImageAsynTaskCallback = loadImageAsynTaskCallback;
	}

	public interface LoadImageAsynTaskCallback {
		
		public boolean beforeLoadImage();

		public void afterLoadImage(Bitmap bitmap);
	}

	/**
	 * 当异步任务执行之前调用
	 */
	@Override
	protected void onPreExecute() {
		// 初始化的操作具体怎么去实现, LoadImageAsynTask 不知道
		// 需要让调用这个 LoadImageAsynTask 的人 去实现
		boolean exists = loadImageAsynTaskCallback.beforeLoadImage();
		super.onPreExecute();
		
		//如果本地缓存已经有图片，就不要去下载
		if(exists){
			this.cancel(true);
		}
	}

	/**
	 * 异步任务执行之后调用
	 */
	@Override
	protected void onPostExecute(Bitmap result) {
		loadImageAsynTaskCallback.afterLoadImage(result);
		super.onPostExecute(result);
	}

	/**
	 * 后台子线程运行的异步任务 String... params 可变长度的参数
	 */
	@Override
	protected Bitmap doInBackground(String... params) {
		try {
			String path = params[0];
			//如果路径为空，就不要去尝试下载图片
			if(path==null && TextUtils.isEmpty(path)){
				return null;
			}
			
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			return BitmapFactory.decodeStream(is);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	

	//从指定URL加载图片
	public static void loadFromUrl(final ImageView imageView,final String url,final String cacheDir){
		if(url==null || url.equals("")){
			return;
		}
		
		new LoadImageAsynTask(new LoadImageAsynTaskCallback() {
			OutputStream out;
			ByteArrayOutputStream baos;
			final String imgName = url.substring(url.lastIndexOf("/") + 1);
			final String dir = Environment.getExternalStorageDirectory()
					.getPath() + "/" + cacheDir+"/";
			//图片是否已经存在 
			boolean exists = false;
			/**
		     * 以最省内存的方式读取本地资源的图片 或者SDCard中的图片
		     * 
		     * @param imagePath
		     *            图片在SDCard中的路径
		     * @return
		     */
		    public Bitmap getSDCardImg(String imagePath) {
	            BitmapFactory.Options opt = new BitmapFactory.Options();
	            opt.inPreferredConfig = Bitmap.Config.RGB_565;
	            opt.inPurgeable = true;
	            opt.inInputShareable = true;
	            // 获取资源图片
	            return BitmapFactory.decodeFile(imagePath, opt);
		    }
			
			@Override
			public boolean beforeLoadImage() {
				//从缓存目录读取一下文件，看看是不是已经存在
				Bitmap bmp = getSDCardImg(dir+imgName);
				exists = (bmp!=null);
				if(exists){
					imageView.setImageBitmap(bmp);
					return true;
				}
				
				// 设置默认背景图片
				imageView.setImageResource(defaultImg);
				return false;
			}

			@Override
			public void afterLoadImage(Bitmap bitmap) {
				if(exists) return;
				
				//如果有SD卡，则保存图片到SD卡上缓存目录
				if (Environment.getExternalStorageState()
						.equals(Environment.MEDIA_MOUNTED) && bitmap!=null) {// sd卡存在
					File fileDir = new File(dir);
					if (!fileDir.exists()) {
						fileDir.mkdirs();
					}
					try {
						File file = new File(fileDir, imgName);
						file.createNewFile();
						out = new FileOutputStream(file);
						baos = new ByteArrayOutputStream();
						bitmap.compress(
								Bitmap.CompressFormat.PNG, 100,
								baos);
						out.write(baos.toByteArray());
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							if (baos != null && out != null) {
								baos.close();
								out.close();
							}

						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				imageView.setImageBitmap(bitmap);
			}
		}).execute(url);
	}

}
